<template>
    <el-container>
    <el-aside width="80%">
                <div>
                    <div class="doctor_seacher">
                            名称:<el-input v-model="search_name" placeholder="请输名称" style="width: 180px"></el-input>                   
                            <el-button type="primary" @click="searche" icon="el-icon-search" style="margin-left:20px">搜索</el-button>
                        </div>
                        <el-divider><i class="el-icon-s-promotion"></i></el-divider>
                <el-table
                    :data="tableData" 
                    border 
                    style="width: 100%" 
                    max-height="320">
                    :default-sort = "{prop: 'id', order: 'descending'}"
                    >
                    <el-table-column
                        type="index">
                    </el-table-column>
                    <el-table-column
                    prop="id"
                    label="ID"
                    sortable
                    width="80">
                    </el-table-column>
                    <el-table-column
                    prop="account"
                    label="账号"
                    width="150">
                    </el-table-column>
                    <el-table-column
                    label="拥有的角色"
                    width="120">
                        <template slot-scope="scope">
                        <span style="margin-left: 10px" v-for="role in scope.row.roles" :key="role.id"
                        >{{ role.name }}<br></span></template>
                    </el-table-column>
                    <el-table-column
                    label="拥有的权限"
                    width="120">
                        <template slot-scope="scope">
                        <span style="margin-left: 10px" v-for="perm in scope.row.perms" :key="perm.id"
                        >{{ perm.name }}<br></span></template>
                    </el-table-column>
                    <el-table-column
                        label="状态"
                        >
                        <template slot-scope="scope">
                        <i class="el-icon-s-opportunity"></i>
                        <span style="margin-left: 10px">{{ scope.row.status=='y'?'可用':'禁用' }}</span>
                    </template>  
                    </el-table-column>
                    <el-table-column
                            fixed="right"
                            label="操作"
                            width="160">
                        <template slot-scope="scope">
                            <el-button
                            size="mini"
                            type="primary" 
                            round
                            @click="handleEdit(scope.row)">编辑</el-button>
                            <el-button
                            size="mini"
                            type="danger"
                            @click="handleDelete(scope.row)">删除</el-button>
                        </template>
                    </el-table-column>
                </el-table>
                <div class="block">
                
                                <el-pagination
                                    @size-change="handleSizeChange"
                                    @current-change="handleCurrentChange"
                                    :current-page="currentPage"
                                    :page-sizes="[2, 4, 6, 8]"
                                    :page-size="4"
                                    layout="total, sizes, prev, pager, next, jumper"
                                    :total="totals">
                                </el-pagination>
                    </div>
                </div>
            </el-aside>
            <el-main>
            <el-button type="primary" @click="add" circle style="width:100%;height:100%">
                <i class="el-icon-circle-plus"></i>添加管理员</el-button>
            <el-drawer
                    :title="opr == 'add'?'增加':'修改'"
                    :before-close="handleClose"
                    :visible.sync="dialog"
                    direction="rtl"
                    custom-class="demo-drawer"
                    ref="drawer"
                    size="50%"
                >
                <div class="demo-drawer__content" align="center" >
                    <el-form :model="form" status-icon :rules="rules" ref="ruleForm" label-width="100px" class="demo-ruleForm">
                        <el-form-item label="账号" prop="account" style="width: 70%">
                            <el-input v-model="form.account" autocomplete="off" ></el-input>
                        </el-form-item>

                        <el-form-item label="密码"  prop="password" style="width: 70%" v-show="show">
                                <el-input type="password" v-model="form.password" autocomplete="off"  
                                        placeholder="请输入密码6--12位"></el-input>
                        </el-form-item> 

                        <el-form-item  label="确认密码" prop="checkPass" style="width: 70%" v-show="show">
                                <el-input type="password" v-model="form.checkPass" autocomplete="off" 
                                       placeholder="请再次输入密码"></el-input>
                        </el-form-item>

                        <el-form-item label="状态" :label-width="formLabelWidth">
                            <select    v-model="form.status" >
                                        <option   value="y">正常</option>
                                        <option   value="n">禁用</option></select>   
                        </el-form-item>
                        
                        <el-divider><i class="el-icon-mobile-phone"></i></el-divider>

                        <el-form-item label="角色" :label-width="formLabelWidth">
                        <el-checkbox-group v-model="form.role_ids">
                        <el-checkbox v-for="role in roles" :key="role.id" :label="role.id" 
                            @change="rolechange">{{role.name}}</el-checkbox>
                        </el-checkbox-group>
                        </el-form-item>  
                        <el-divider><i class="el-icon-mobile-phone"></i></el-divider>
                        <el-form-item label="角色包含的权限" :label-width="formLabelWidth">
                        <el-checkbox-group v-model="permlist" >
                        <el-checkbox disabled v-for="perm in perms" :key="perm.id" :label="perm.id"
                            >{{perm.name}}</el-checkbox>
                        </el-checkbox-group>
                        </el-form-item>  

                        <el-divider><i class="el-icon-mobile-phone"></i></el-divider>
                    </el-form>
                        <div class="demo-drawer__footer">
                        <el-button @click="$refs.drawer.closeDrawer()">取 消</el-button>
                        <el-button @click="resetForm" v-show="show">重置</el-button>
                        <el-button type="primary" @click="submit('ruleForm')" :loading="loading">{{ loading ? '提交中 ...' : '确 定' }}</el-button>
                        </div>
                </div>
            </el-drawer>
            </el-main>
    </el-container>
</template>
<script>
const axios = require("axios");
  export default {
    data() {
         //校验密码
         var validatePass = (rule, value, callback) => {
        if (value === '') {
          callback(new Error('请输入密码'));
        }else if(value.length>12 || value.length<6){
            callback(new Error('密码长度在6--12位'));
        
        } else {
          if (this.form.checkPass !== '') {
            this.$refs.ruleForm.validateField('checkPass');
          }
          callback();
        }
      };
      var validatePass2 = (rule, value, callback) => {
        if (value === '') {
          callback(new Error('请再次输入密码'));
        } else if (value !== this.form.password) {
          callback(new Error('两次输入密码不一致!'));
        } else {
          callback();
        }
      };
      return {
        show: true,
        opr:'',
        tableData: [],
        search_name: "",
        currentPage: 1,
        pagesize:4,
        totals:0,
        dialog: false,
        loading: false,
        perms: [],
        roles: [],
        permlist :[],
        form: {
            id: '0',
            account: '',
            password: '',
            checkPass:'',
            status:'y',
            role_ids: []   
      },
      rules: {
            account: [
                    { required: true, message: '请输入账号', trigger: 'blur' },
                    { min: 6, max: 12, message: '长度在 6 到 12 个字符', trigger: 'blur' }
                    ],
          password: [
                        { validator: validatePass, trigger: 'blur' }
                    ],
          checkPass: [
                    { validator: validatePass2, trigger: 'blur' }
                    ],
        },
      formLabelWidth: '80px',
      timer: null,
      }
    },
    methods: {
        rolechange(){
             this.permlist= [];
             this.roles.forEach(r=>{
                 if(this.form.role_ids.indexOf(r.id) > -1){
                      r.perms.forEach(p=>{
                            this.permlist.push(p.id)
                        })
                 }
             })
           this.permlist = [ ...new Set( this.permlist ) ];//添加权限并去重
        },
        add(){
            this.opr='add';
            this.show=true;
            //查询权限
            axios.get("http://192.168.6.189:8080/hpl-perm/list").then((r) => {
                if(r.data.code === 200){
                     this.perms = r.data.data;
                     this.dialog=true;  
                }else if(r.data.code === 403){
                                this.$notify({
                                    title: '警告',
                                    message: '没有查询权限的权限',
                                    type: 'warning'
                                    }); 
                            }else if(r.data.code === 500){
                                this.$notify({
                                    title: '警告',
                                    message: r.data.msg,
                                    type: 'warning'
                                    }); 
                            }else{
                                this.$notify({
                                    title: '警告',
                                    message: '系统繁忙！',
                                    type: 'warning'
                                    }); 
                            }
            })
            //查询角色
            axios.get("http://192.168.6.189:8080/hpl-role/list").then((r) => {
                if(r.data.code == 200){
                     this.roles = r.data.data;
                     this.dialog=true;  
                }else if(r.data.code === 403){
                                this.$notify({
                                    title: '警告',
                                    message: '没有查询角色权限',
                                    type: 'warning'
                                    }); 
                            }else if(r.data.code === 500){
                                this.$notify({
                                    title: '警告',
                                    message: r.data.msg,
                                    type: 'warning'
                                    }); 
                            }else{
                                this.$notify({
                                    title: '警告',
                                    message: '系统繁忙！',
                                    type: 'warning'
                                    }); 
                            }
            })
            
        },
        handleEdit(row) {
            this.add();
            this.show=false;
            this.opr='update';
            this.form.id = row.id;
            this.form.account=row.account;
            this.form.password=row.password;
            this.form.checkPass=row.password;
            this.form.status = row.status;
            row.roles.forEach(r=>{
                this.form.role_ids.push(r.id);
            })
            this.rolechange();
           console.log(this.form)
            
        },
        handleDelete(row) {
            console.log( row);
            if(confirm("你确定要删除吗？")){
                axios.get("http://192.168.6.189:8080/hpl-admin/del?id="+row.id).then((r) => {
                            if(r.data.code === 200){
                                this.$message({
                                message: '删除成功，这是一条成功消息',
                                    type: 'success'
                                    });	
                                    this.searche(); 
                            }else if(r.data.code === 403){
                                this.$notify({
                                    title: '警告',
                                    message: '没有删除权限',
                                    type: 'warning'
                                    }); 
                            }else if(r.data.code === 500){
                                this.$notify({
                                    title: '警告',
                                    message: r.data.msg,
                                    type: 'warning'
                                    }); 
                            }else{
                                this.$notify({
                                    title: '警告',
                                    message: '系统繁忙！',
                                    type: 'warning'
                                    }); 
                            }
                        })
            }
        },
        handleClose(done) {
        this.$confirm('确认关闭？')
                .then(() => {
                    this.cancelForm();
                    done();
                })
                .catch(() => {});
            },
        resetForm() {
                this.form.account='';
                this.form.id='0';
                this.form.status='y'
                this.form.role_ids=[];
                this.permlist=[];
                this.form.password= '';
                this.form.checkPass='';
            },
        submit(formName) {
            this.$refs[formName].validate((valid) => {
                if (valid) {
                    if (this.loading) {
                        return;
                    }
                    this.$confirm('确定要提交表单吗？')
                        .then(()=> {
                        this.loading = true;
                        let admin = this.form;
                        admin.roles=[];
                        this.form.role_ids.forEach(i=>{
                            admin.roles.push({id: i});
                        })
                        axios.post("http://192.168.6.189:8080/hpl-admin/"+this.opr,this.form).then(r=>{
                            if(r.data.code === 200){
                                        this.$message({
                                        message: '添加成功，这是一条成功消息',
                                            type: 'success'
                                            });	
                                            this.searche();
                                            this.cancelForm();                                  
                                    }else if(r.data.code === 403){
                                        this.$notify({
                                            title: '警告',
                                            message: r.data.msg,
                                            type: 'warning'
                                            }); 
                                    }else if(r.data.code === 500){
                                this.$notify({
                                    title: '警告',
                                    message: r.data.msg,
                                    type: 'warning'
                                    }); 
                            }else{
                                this.$notify({
                                    title: '警告',
                                    message: '系统繁忙！',
                                    type: 'warning'
                                    }); 
                            } 
                            })
                        this.timer = setTimeout(() => {
                            // 动画关闭需要一定的时间
                            setTimeout(() => {
                            this.loading = false;
                            }, 400);
                        }, 2000);
                        })
                        .catch();
                } else {
                                this.$notify({
                                    title: '警告',
                                    message: '数据格式有误！',
                                    type: 'warning'
                                    }); 
                    return false;
                }
            });
        },
        cancelForm() {
            this.loading = false;
            this.dialog = false;
            this.resetForm();
            clearTimeout(this.timer);
            
        },
        handleSizeChange(val) {
                this.pagesize=val;
                this.searche();
            },
        handleCurrentChange(val) {
                this.currentPage=val;
                this.searche();
            },
       searche(){
          axios.get("http://192.168.6.189:8080/hpl-admin/list?currentPage="
            +this.currentPage+"&pagesize="+this.pagesize+"&account="+this.search_name).then((r) => {
                if(r.data.code == 200){
                     this.tableData = r.data.data.records;
                        this.totals= r.data.data.total;
                }else if(r.data.code === 403){
                                this.$notify({
                                    title: '警告',
                                    message: '没有查询管理员的权限',
                                    type: 'warning'
                                    }); 
                            }else if(r.data.code === 500){
                                this.$notify({
                                    title: '警告',
                                    message: r.data.msg,
                                    type: 'warning'
                                    }); 
                            }else{
                              this.$notify({
                                    title: '警告',
                                    message: '系统繁忙！',
                                    type: 'warning'
                                    });  
                            }
            })
      }
    },
    mounted(){
            this.searche();
    }

  }
</script>